#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>
#include <pthread.h>

#include "InetAddr.hpp"
#include "Log.hpp"

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR
};

const static int defaultsockfd = -1;
const static int gbacklog = 16;

// 声明
class TcpServer;

class ThreadData
{
public:
    ThreadData(int fd, InetAddr addr, TcpServer *s)
        : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

using func_t = std::function<std::string(const std::string &)>;

    class TcpServer
{
public:
    TcpServer(int port, func_t func)
        : _port(port),
          _listensock(defaultsockfd),
          _isrunning(false),
          _func(func)
    {
    }

    void InitServer()
    {
        // 1 创建套接字
        // tcp
        _listensock = ::socket(AF_INET, SOCK_STREAM, 0);

        if (_listensock < 0)
        {
            LOG(ERROR, "socket error");
            exit(1);
        }
        LOG(DEBUG, "socket success,socketfd is : %d\n", _listensock);

        // 2 bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = ::bind(_listensock, (struct sockaddr *)&local, sizeof(local));

        if (n < 0)
        {
            LOG(FATAL, "bind error");
            exit(2);
        }
        LOG(DEBUG, "bind success, socketfd is : %d\n", _listensock);

        // 3 先建立连接
        // tcpserver 启动 一直等待client连接
        n = ::listen(_listensock, gbacklog);

        if (n < 0)
        {
            LOG(FATAL, "listen error");
            exit(LISTEN_ERROR);
        }

        LOG(DEBUG, "listen success, socketfd is : %d\n", _listensock);
    }

    void Service(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link , info %s:%d , fd:%d\n", client.GetIp().c_str(), client.GetPort(), sockfd);

        std::string clientaddr = "[" + client.GetIp() + ":" + std::to_string(client.GetPort()) + "]#";

        while (true)
        {
            char buffer[1024];
            // ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            ssize_t n = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << clientaddr << buffer << std::endl;

                // 发回一样的消息
                std::string result = _func(buffer);

                send(sockfd, result.c_str(), result.size(), 0);
                // write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                // client 退出&&关闭连接
                LOG(INFO, "%s quit\n", clientaddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n");
                break;
            }
        }

        ::close(sockfd);
    }

    // IO和业务解耦
    static void *ThreadFunc(void *args)
    {

        pthread_detach(pthread_self());
        ThreadData *data = static_cast<ThreadData *>(args);
        data->self->Service(data->sockfd, data->clientaddr);
        delete data;
        return nullptr;
    }

    void Loop()
    {
        _isrunning = true;
        // 4 不能直接接受数据，先获取连接
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 接受一个连接请求
            int sockfd = ::accept(_listensock, (struct sockaddr *)&peer, &len);

            if (sockfd < 0)
            {
                LOG(FATAL, "accept error\n");
                continue;
            }

            pthread_t t;
            ThreadData *data = new ThreadData(sockfd, InetAddr(peer), this);
            // data是传给(void*)ThreadFunc的参数
            pthread_create(&t, nullptr, ThreadFunc, data); // 线程分离
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
        if (_listensock > defaultsockfd)
            ::close(_listensock);
    }

private:
    uint16_t _port;
    int _listensock; // 监听套接字
    bool _isrunning;

    func_t _func;
};
